<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\goods\Goods as GoodsModel;
use app\admin\model\Coupons as CouponsModel;
use app\admin\model\user\Coupons as UserCouponsModel;
use think\cache\driver\Redis;
use think\Db;

/**
 * 优惠券接口
 */
class Coupons extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = ['*'];

    /**
     * 优惠券列表
     *
     */
    public function list()
    {
        $CouponsModel = new CouponsModel();
        $list = $CouponsModel->where('gettimeend','>',datetime(time()))->select();


        $this->success('请求成功',$list);
    }

    /*
     * 领取优惠券
     * */
    public function getCoupons()
    {
        $id = $this->request->post('id',0);
        $coupons = CouponsModel::where(['id'=>$id])->find();
        $Redis = new Redis();
        if ($Redis->get('coupons_'.$this->auth->id.'_'.$id)){
            $this->error('请勿频繁点击');
        }else{
            $Redis->set('coupons_'.$this->auth->id.'_'.$id,$this->auth->id.'_'.$id,5);
        }

        if (!$coupons){
            $this->error('优惠券不存在');
        }
        //验证用户是否已领取过
        $user_coupons_num = UserCouponsModel::where(['user_id'=>$this->auth->id,'coupons_id'=>$coupons['id']])->count();
        if ($user_coupons_num>=$coupons['limit']){
            $this->error('您已领取过');
        }
        //验证领取时间
        if (datetime(time())>$coupons['gettimeend']){
            $this->error('已过领取时间');
        }
        //验证库存
        if ($coupons['stock']<=0){
            $this->error('优惠券被领完了~');
        }

        // 启动事务
        Db::startTrans();
        try{
            //发放优惠券
            UserCouponsModel::create([
                'user_id' => $this->auth->id,
                'coupons_id' => $coupons['id'],
                'createtime' => time(),
            ]);
            //扣库存
            $coupons->setDec('stock',1);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        $this->success('请求成功');
    }

    /**
     * 我的优惠券
     */
    public function myCoupons()
    {
        $type = $this->request->get('type','');
        $goods_id = $this->request->get('goods_id',0);
        $where = [];
        if ($type=='all'){

        }elseif ($type=='used'){
//            $where['maincoupons.usetime'] = ['<>',null];
            $where['fa_user_coupons.use_order_id'] = ['>',0];
        }elseif ($type=='expire'){
            $where['maincoupons.usetimeend'] = ['<',datetime(time())];
        }else{

        }

//        if ($goods_id){
//            $where['goods_ids'] = ['FIND_IN_SET($goods_id,goods_ids)'];
//        }
        $where['user_id'] = $this->auth->id;
        $list = UserCouponsModel::with(['maincoupons'])->where($where)->select();
        if ($goods_id){
            $goods_id_arr = CouponsModel::where(" FIND_IN_SET($goods_id,goods_ids) OR goods_ids=0")->column('id');
            $now = time();
            foreach ($list as $key=>$value)
            {
                if (!in_array($value['coupons_id'],$goods_id_arr)){
                    //去掉不可用商品的券
                    unset($list[$key]);

                }else{
                    if ($value['use_order_id']>0 || $value['use_order_id']!=null){
                        //去掉已使用的
                        unset($list[$key]);
                    }else{
                        if ($value['maincoupons']['usetime']!=0){
                            $end_tim = $value['createtime'] + ($value['maincoupons']['usetime']*24*60*60);
                            if ($end_tim<$now){
                                //去掉过了使用天数的
                                unset($list[$key]);
                            }
                        }else{
                            if (strtotime($value['maincoupons']['usetimeend'])<$now || $now<strtotime($value['maincoupons']['usetimestart'])){
//                                var_dump($value['id']);
//                                var_dump($value['maincoupons']['usetimeend']);
                                //去掉过了使用截止日期的
                                unset($list[$key]);
                            }
                        }
                    }
                }

            }
        }

        $this->success('请求成功',$list);
    }
}
